package one.stand.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import one.stand.util.IpUtil;
import one.stand.zuul.util.RateLimiter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.LongAdder;

/**
 * AccessFilter
 * Created by chengjiarui on 2019-06-11.
 */
public class AccessFilter extends ZuulFilter {
    private static final Logger log = LoggerFactory.getLogger(AccessFilter.class);
    private RateLimiter rateLimiter;

    public static LongAdder longAdder = new LongAdder();

    public AccessFilter(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String ip = IpUtil.getIpAddr(request);
        String requestURL = request.getRequestURI();
        String token = StringUtils.defaultIfBlank(request.getHeader("token"), request.getHeader(HttpHeaders.AUTHORIZATION));
        String data = request.getParameter("data");
        log.info("request: ({} {} {}) {} {}", request.getMethod(), ip, token, requestURL, data);

//         限流
//        String key = ip + requestURL + token + data;
//        if (!rateLimiter.tryRequire(key)) {
//            throw new OneZuulException(ResultEnum.FREQUENTLY);
//        }
        longAdder.add(1);

        // 授权
        // 验参

        return null;
    }
}
